<template>
	<view class="main-content">
		<MHeader>{{ state.pageName }}</MHeader>
		<scroll-view scroll-y="true" style="height: calc(100% - 180rpx)">
			<view>
				<item name="组织" sign must>
					<!-- <input class="input" v-model="state.info.Data.Model.F_QUQY_ORGName" disabled placeholder="请选择" @click.native="choose('ORG_Organizations', 'F_QUQY_OrgId', 'FNumber', 'F_QUQY_ORGName', 'FNumber', 'FName')" /> -->
					<input class="input" v-model="state.info.Data.Model.F_QUQY_ORGName" disabled placeholder="请选择" />
				</item>
				<item name="养殖批次" sign must>
					<input class="input" v-model="state.info.Data.Model.F_QUQY_BreedingContractName"  placeholder="请选择" @click.native="choose('BAS_PreBaseDataOne', 'F_QUQY_BreedingContract', 'FNUMBER', 'F_QUQY_BreedingContractName', 'FNumber', 'FName')" />
				</item>
				<item name="客户">
					<input class="input" v-model="state.info.Data.Model.F_QUQY_CustomerName" disabled placeholder="养殖批次自动带出" />
				</item>
				<item name="客户电话">
					<input class="input" v-model="state.info.Data.Model.F_QUQY_CustTelephone" type="number" placeholder="请输入" />
				</item>
				<item name="客户地址">
					<input class="input" v-model="state.info.Data.Model.F_QUQY_CustAddress" placeholder="请输入" />
				</item>
				<item name="技术员" sign must>
					<!-- <input class="input" v-model="state.info.Data.Model.F_QUQY_TechnicianName" disabled placeholder="请选择" @click.native="choose('BD_Empinfo','F_QUQY_Technician','FSTAFFNUMBER','F_QUQY_TechnicianName','FNumber','FName')" /> -->
					<input class="input" v-model="state.info.Data.Model.F_QUQY_TechnicianName" disabled placeholder="自动带出" />
				</item>
				<item name="日期" sign must>
					<input class="input" v-model="state.info.Data.Model.F_QUQY_Date"  @click="chooseT('F_QUQY_Date')" placeholder="请选择" />
				</item>
				<item name="是否退药">
					<van-switch v-model="state.info.Data.Model.F_QUQY_DrugRepercussion" size="24"></van-switch>
				</item>
			</view>
			<MHeader hidTag>
				<van-icon name="cluster" color="#1989fa" style="margin-right: 10rpx" />
				兽药列表
				<template #right>
					<van-icon name="add-o" size="20" @click="appendItem" />
				</template>
			</MHeader>
			<view style="padding-bottom: 10rpx">
				<view class="card" v-for="(item, index) in state.info.Data.Model.FEntity">
					<view class="card-index">{{ index + 1 }}</view>
					<item name="药物" sign must @longpress="longpress(item, index)">
						<input class="input" v-model="item.F_QUQY_MedicinalName"  placeholder="请选择" @click.native="choose('BD_MATERIAL', 'F_QUQY_Medicinal', 'FNUMBER', 'F_QUQY_MedicinalName', 'FNumber', 'FName', '101204,102799,102800,102801',null,item)" />
					</item>
					<item name="基本单位">
						<input class="input" v-model="item.F_QUQY_BaseUnitName" disabled placeholder="自动带出" />
					</item>
					<van-field v-model="item.F_QUQY_Qty" type="number" label="数量" placeholder="请输入" />
					<!-- <item name="数量">
						<input class="input" v-model="item.F_QUQY_Qty" type="number" placeholder="请输入" />
					</item> -->
					<item name="含税单价">
						<input class="input" v-model="item.F_QUQY_Price" type="number" placeholder="请输入" style="padding-right: 35rpx" />
						<text class="symbol">元</text>
					</item>
					<item name="仓库" sign must>
						<input class="input" v-model="item.F_QUQY_VDStockName"  placeholder="请选择" @click.native="choose('QUQY_VeterinaryDrugStock', 'F_QUQY_VDStock', 'FNUMBER', 'F_QUQY_VDStockName', 'FNumber', 'FName',null,null,item)" />
					</item>
				</view>
			</view>
		</scroll-view>
		<view class="btns">
			<van-button type="primary" size="small" @click="save">保 存</van-button>
		</view>
	</view>
	<ChooseTime ref="chooseTime" />
	<Loading v-if="state.loading" />
</template>

<script setup>
	import moment from 'moment'
	import { reactive, getCurrentInstance, ref, watch, nextTick } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import { checkForm } from '/utils/utils.js'
	import kdApis from '/api/modularApi/kdApi.js'
	import { confirm, msg } from '/utils/utils.js'
	import { includes } from 'lodash-es'
	const { proxy } = getCurrentInstance()
	const state = reactive({
		loading: true,
		info: {
			FormId: 'QUQY_VeterinaryMedicineApplication',
			Data: {
				Model: {
					F_QUQY_DrugRepercussion: false,
					FEntity: [],
					F_QUQY_OrgId: {
						FNumber: null
					},
					F_QUQY_Customer: {
						FNUMBER: null
					},
					F_QUQY_BreedingContract: {
						FNUMBER: null
					},
					F_QUQY_Technician: {
						FSTAFFNUMBER: null
					}
				}
			}
		},
		rules: {
			F_QUQY_ORGName: '请选择组织！',
			F_QUQY_BreedingContractName: '请选择养殖批次！',
			F_QUQY_TechnicianName: '请选择技术员！',
			F_QUQY_Date: '请选择日期！',
		},
		pageName: '兽药申请'
	});

	const chooseTime = ref(null)
	const chooseT = (fieldName) => {
		chooseTime.value.start(state.info.Data.Model, fieldName);
	}

	// 1.组织控制（使用组织为当前选择的组织）：养殖批次
	const choose = (FormId, Field, FieldSon, FieldName, IdKey, IdKeyName, Group, BringOther, row) => {
		// 🐟 选择组织前
		if (Field == 'F_QUQY_OrgId') {

		}

		// 🐟 1
		let mustHasOrg = ['F_QUQY_BreedingContract', 'F_QUQY_Medicinal', 'F_QUQY_VDStock', 'F_QUQY_Technician']
		if (mustHasOrg.includes(Field)) {
			if (!state.info.Data.Model.F_QUQY_ORGName) return msg('请先选择组织！')
		}

		// 🐟 选择仓库需先选择技术员，仓库不要公司仓
		if (Field == 'F_QUQY_VDStock') {
			if (!state.info.Data.Model.F_QUQY_TechnicianName) return msg('请先选择技术员！')
		}

		uni.navigateTo({
			url: `/pages/baseList/BaseList?FormId=${FormId}&isChoose=1&Group=${Group||''}&Name=请选择`,
			success: res => { res.eventChannel.emit('fun', [fun, 'jc']) }
		})

		// 回调方法
		let fun = (list) => {
			if (row) {
				// 🍕 子集里的
				row[Field][FieldSon] = list[0][IdKey]
				row[FieldName] = list[0][IdKeyName]

				if (Field == 'F_QUQY_Medicinal') {
					// 🍕 查询物料库存单位，不传，后端自动带出
					kdApis.formQuery({
						data: {
							FormId: 'BD_UNIT',
							FieldKeys: 'FName,FNumber,FUNITID',
							FilterString: [{ "Left": "(", "FieldName": "FUNITID", "Compare": "=", "Value": list[0].FStoreUnitID, "Right": ")", "Logic": "and" }]
						}
					}).then(res => {
						if (res && res.length) {
							row.F_QUQY_BaseUnitName = res[0].FName
						}
					})
				}
			} else {
				state.info.Data.Model[Field][FieldSon] = list[0][IdKey]
				state.info.Data.Model[FieldName] = list[0][IdKeyName]
				if (BringOther) {
					state.info.Data.Model[BringOther[0]] = list[0][BringOther[1]]
				}

				if (Field == 'F_QUQY_BreedingContract') {
					// 🍕 带出技术员
					state.info.Data.Model.F_QUQY_CustomerName = list[0]['F_QUQY_Saleman.Fname']
					state.info.Data.Model.F_QUQY_Customer.FNUMBER = list[0]['F_UTPA_Base.FNumber']
					// 🍕 带出电话、地址
					state.info.Data.Model.F_QUQY_CustTelephone = list[0].F_UTPA_Text
					state.info.Data.Model.F_QUQY_CustAddress = list[0].F_UTPA_Text2
				}

			}

			// 🐟 选择组织后
			if (Field == 'F_QUQY_OrgId') {
				// 🍕 初始化 养殖批次等字段及其带出的字段
				for (let key in state.info.Data.Model) {
					let value = state.info.Data.Model[key]
					if (mustHasOrg.includes(key) && value) {
						if (typeof(value) === 'object') {
							for (let k in value) { value[k] = null }
							state.info.Data.Model[`${key}Name`] = null
							if (state.info.Data.Model[`${key}TEM`]) state.info.Data.Model[`${key}TEM`] = null // 带出的字段
						} else {
							value = null
						}
					}
				}

				// 🍕 初始化子集
				if (state.info.Data.Model.FEntity.length) {
					for (let it of state.info.Data.Model.FEntity) {
						it.F_QUQY_MedicinalName = null
						it.F_QUQY_Medicinal = {
							FNUMBER: null
						}
						it.F_QUQY_BaseUnitName = null
						it.F_QUQY_VDStock = {
							FNUMBER: null
						}
						F_QUQY_VDStockName: null
					}
				}
			}
		}
	}

	const appendItem = () => {
		let obj = {
			F_QUQY_MedicinalName: null,
			F_QUQY_Medicinal: {
				FNUMBER: null
			},
			F_QUQY_BaseUnitName: null,
			F_QUQY_Price: null,
			F_QUQY_Amount: null,
			F_QUQY_VDStock: {
				FNUMBER: null
			},
			F_QUQY_VDStockName: null,
			F_QUQY_Qty: null,
		}
		state.info.Data.Model.FEntity.push(obj)
	}

	const longpress = (item, index) => {
		let msg = item.F_QUQY_MedicinalName ? `请确认删除 [ ${item.F_QUQY_MedicinalName} ] ？` : '请确认删除 ？'
		confirm(msg).then(() => {
			state.info.Data.Model.FEntity.splice(index, 1)
		}).catch(() => {})
	}

	const save = async () => {
		// await checkForm(state.info.Data.Model, state.rules)
		state.info.Data.Model.F_QUQY_DrugRepercussion = Number(state.info.Data.Model.F_QUQY_DrugRepercussion)
		// 🍕 至少一个子集 && 必填项
		if (state.info.Data.Model.FEntity.length == 0) return msg('请至少选择一种兽药！')
		let flag = true
		state.info.Data.Model.FEntity.forEach((it, i) => {
			if (!it.F_QUQY_MedicinalName) {
				flag = false
				return msg(`请选择药物（卡片${i+1}）！`)
			}
			if (!it.F_QUQY_VDStockName) {
				flag = false
				return msg(`请选择仓库（卡片${i+1}）！`)
			}
		})
		if (!flag) return
		kdApis.formSave(state.info).then((res) => {
			if (res) {
				msg('保存成功！')
				setTimeout(() => {
					uni.navigateBack()
				}, 300)
			}
		})
	}
	const getDetails = (Id) => {
		kdApis.formView({
			formId: 'QUQY_VeterinaryMedicineApplication',
			data: { Id }
		}).then((res) => {
			if (res) {
				let obj = {
					FId: res.Id,
					F_QUQY_OrgId: {
						FNumber: res.F_QUQY_OrgId?.Number
					},
					F_QUQY_ORGName: res.F_QUQY_OrgId?.Name[0].Value,
					F_QUQY_BreedingContract: {
						FNUMBER: res.F_QUQY_BreedingContract?.Number
					},
					F_QUQY_BreedingContractName: res.F_QUQY_BreedingContract?.Name[0].Value,
					F_QUQY_Customer: {
						FNUMBER: res.F_QUQY_Customer?.Number
					},
					F_QUQY_CustomerName: res.F_QUQY_Customer?.Name[0].Value,
					F_QUQY_CustTelephone: res.F_QUQY_CustTelephone,
					F_QUQY_CustAddress: res.F_QUQY_CustAddress,
					F_QUQY_Technician: {
						FSTAFFNUMBER: res.F_QUQY_Technician?.Number
					},
					F_QUQY_TechnicianName: res.F_QUQY_Technician?.Name[0].Value,
					F_QUQY_Date: moment(res.F_QUQY_Date).format('YYYY-MM-DD'),
					F_QUQY_DrugRepercussion: Boolean(Number(res.F_QUQY_DrugRepercussion)),
					FEntity: res.FEntity.map(it => {
						return {
							F_QUQY_Medicinal: {
								FNUMBER: it.F_QUQY_Medicinal?.Number
							},
							F_QUQY_MedicinalName: it.F_QUQY_Medicinal?.Name[0].Value,
							F_QUQY_BaseUnitName: it.F_QUQY_BaseUnit?.Name[0].Value,
							F_QUQY_Qty: it.F_QUQY_Qty,
							F_QUQY_Price: it.F_QUQY_Price,
							F_QUQY_Amount: it.F_QUQY_Amount,
							F_QUQY_VDStock: {
								FNUMBER: it.F_QUQY_VDStock?.Number
							},
							F_QUQY_VDStockName: it.F_QUQY_VDStock?.Name[0].Value
						}
					})
				}
				Object.assign(state.info.Data.Model, obj)
				state.loading = false
			}
		})
	}
	onLoad(async (query) => {
		if (query.Id) {
			state.pageName = '兽药申请编辑'
			getDetails(query.Id)
		} else {
			// 🍕 日期默认当前日期
			state.info.Data.Model.F_QUQY_Date = moment(new Date()).format('YYYY-MM-DD')
			// 🍕 技术员默认当前人
			let memberInfo = uni.getStorageSync('memberInfo')
			state.info.Data.Model.F_QUQY_Technician = {
				FSTAFFNUMBER: memberInfo.Number
			}
			state.info.Data.Model.F_QUQY_TechnicianName = memberInfo.Name[0].Value
			// 🍕 组织默认当前人组织
			state.info.Data.Model.F_QUQY_OrgId = {
				FNumber: memberInfo.UseOrgId.Number
			}
			state.info.Data.Model.F_QUQY_ORGName = memberInfo.UseOrgId.Name[0].Value
			state.loading = false
		}
	})
</script>
<style lang="scss" scoped>
	.card {
		position: relative;
		width: calc(100% - 60rpx);
		margin: 20rpx auto;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		border-radius: 6rpx;

		.card-index {
			position: absolute;
			display: flex;
			// align-items: center;
			// justify-content: center;
			width: 40rpx;
			height: 40rpx;
			padding-left: 10rpx;
			font-size: 24rpx;
			background: #409eff;
			color: #fff;
			clip-path: polygon(0 0, 0 40rpx, 10rpx 40rpx, 40rpx 10rpx, 40rpx 0);
		}
	}
</style>
<style lang="scss" scoped>
	::v-deep .van-field {
		border-bottom: 1rpx solid #e9e9ea;
	}
	::v-deep .van-field__label {
		color: #000 !important;
	}
	::v-deep .van-field__control {
		text-align: right;
	}
	::v-deep .van-field__control::-webkit-input-placeholder {
	    color: gray;
	}
</style>